<?php

namespace app\common\service\award;
use app\api\service\user\UserService;
use app\common\enum\CommEnum;
use app\common\enum\order\OrderAwardEnum;
use app\common\enum\order\OrderPayStatusEnum;
use app\common\enum\order\OrderStatusEnum;
use app\common\enum\user\balanceLog\BalanceLogSceneEnum;
use app\common\model\order\Order;
use app\common\model\order\OrderAward;
use app\common\model\settings\Setting;
use app\common\model\user\BalanceLog;
use app\common\model\user\GradeAgent;
use app\common\model\user\User;
use app\shop\model\plus\model\AgentSet;

/**
 * 奖励服务
 * Class AwardService
 * buyer 买家userModel
 * ind_set 单独奖励设置
 */
class AwardService
{
    public function agentAward($buyer, $payment, $ind_set = [])
    {
        $agents = UserService::getAgents($buyer->user_id);
        if (!$agents) {      //没有上级
            return [];
        }
        if ($payment <= 0) {
            return [];
        }
        $award = [];
        $app_id = $buyer->app_id;
        $agent_set = AgentSet::find($app_id);
        $level = $agent_set['level'];
        //等级奖励
        $grade_award = GradeAgent::where("app_id", $app_id)->column("*", "grade_id");
        //内置奖励设置
        $ind_set = array_merge([
            "first_money" => 0,
            "second_money" => 0,
            "third_money" => 0,
            "agent_money_type" => CommEnum::AWARD_MONEY,
        ], $ind_set);
        //一级奖励
        $first_money = 0;
        $referer = $agents[0];
        $first_grade_award = $grade_award[$referer->grade_id] ?? [];
        if ($ind_set['first_money'] > 0) {
            if ($ind_set['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                $first_money = $ind_set['first_money'];
            } else if ($ind_set['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                $first_money = $payment * $ind_set['first_money'] / 100;
            }
        } elseif ($first_grade_award['first_money'] > 0) {
            if ($first_grade_award['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                $first_money = $first_grade_award['first_money'];
            } else if ($first_grade_award['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                $first_money = $payment * $first_grade_award['first_money'] / 100;
            }
        } elseif ($agent_set['first_rate'] > 0) {
            $first_money = $payment * $agent_set['first_rate'] / 100;
        }
        $first_money = round($first_money, 2);
        if ($first_money > 0) {
            $award[] = [
                'user_id' => $referer->user_id,
                'money' => $first_money,
                'level' => 1,
                'grade' => $referer->grade_id,
                'app_id' => $app_id,
            ];
        }
        //二级奖励
        if ($level >= 2) {
            $second_money = 0;
            $second_user = $agents[1] ?? null;
            if ($second_user) {
                $second_grade_award = $grade_award[$second_user->grade_id] ?? [];
                if ($ind_set['second_money'] > 0) {
                    if ($ind_set['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                        $second_money = $ind_set['second_money'];
                    } else if ($ind_set['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                        $second_money = $payment * $ind_set['second_money'] / 100;
                    }
                } elseif ($second_grade_award['second_money'] > 0) {
                    if ($second_grade_award['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                        $second_money = $second_grade_award['second_money'];
                    } else if ($second_grade_award['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                        $second_money = $payment * $second_grade_award['second_money'] / 100;
                    }
                } elseif ($agent_set['second_rate'] > 0) {
                    $second_money = $payment * $agent_set['second_rate'] / 100;
                }
                $second_money = round($second_money, 2);
                if ($second_money > 0) {
                    $award[] = [
                        'user_id' => $second_user->user_id,
                        'money' => $second_money,
                        'level' => 2,
                        'grade' => $second_user->grade_id,
                        'app_id' => $app_id,
                    ];
                }
                //三级奖励
                if ($level >= 3) {
                    $third_money = 0;
                    $third_user = $agents[2] ?? null;
                    if ($third_user) {
                        $third_grade_award = $grade_award[$third_user->grade_id] ?? [];
                        if ($ind_set['third_money'] > 0) {
                            if ($ind_set['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                                $third_money = $ind_set['third_money'];
                            } else if ($ind_set['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                                $third_money = $payment * $ind_set['third_money'] / 100;
                            }
                        } elseif ($third_grade_award['third_money'] > 0) {
                            if ($third_grade_award['agent_money_type'] == CommEnum::AWARD_MONEY) {        //固定金额
                                $third_money = $third_grade_award['third_money'];
                            } else if ($third_grade_award['agent_money_type'] == CommEnum::AWARD_RATE) {    //比例
                                $third_money = $payment * $third_grade_award['third_money'] / 100;
                            }
                        } elseif ($agent_set['third_rate'] > 0) {
                            $third_money = $payment * $agent_set['third_rate'] / 100;
                        }
                        $third_money = round($third_money, 2);
                        if ($third_money > 0) {
                            $award[] = [
                                'user_id' => $third_user->user_id,
                                'money' => $third_money,
                                'level' => 3,
                                'grade' => $third_user->grade_id,
                                'app_id' => $app_id,
                            ];
                        }
                    }
                }
            }
        }
        return $award;
    }

    public static function payAward($order_id)
    {
        $order = Order::find($order_id);
        if (!$order) {
            return [
                'error' => 1,
                'msg' => '订单不存在'
            ];
        }
        $pay_status = $order->pay_status['value'];
        $order_status = $order->order_status['value'];
        $app_id = $order->app_id;
        $trade_set = Setting::getItem("trade", $app_id);
        $award_timing = $trade_set['award_timing'];
        if ($pay_status != OrderPayStatusEnum::SUCCESS || ($order_status != OrderStatusEnum::COMPLETED && $order_status != OrderStatusEnum::NORMAL)) {
            return [
                'error' => 1,
                'msg' => '订单未支付或已取消'
            ];       //订单未支付或订单状态不是交易中或已完成跳过
        }
        if ($award_timing == OrderAwardEnum::AWARD_TIMING_CONFIRMED && $order_status != OrderStatusEnum::COMPLETED) {
            return [
                'error' => 1,
                'msg' => '订单未完成'
            ];  //如果是订单完成发放奖励，订单状态不是已完成跳过
        }
        $award = OrderAward::where([['order_id', '=', $order_id], ['pay_status', '=', 0]])->select();
        if (!$award) {
            return [
                'error' => 1,
                'msg' => '没有奖励数据'
            ];
        }
        $award->each(function ($item) use ($order, $app_id) {
            $user = User::find($item->user_id);
            if (!$user) {
                return true;
            }
            $user->startTrans();
            try {
                $user->balance = $user->balance + $item->money;
                // 更新账户余额
                $user->save();
                //设为已发放
                $item->pay_status = 1;
                $item->save();
                // 新增余额变动记录
                BalanceLog::add(BalanceLogSceneEnum::ORDER_AWARD, [
                    'user_id' => $item->user_id,
                    'money' => $item->money,
                    'remark' => "",
                    'app_id' => $app_id
                ], [$order->order_no]);
                $user->commit();
                return true;
            } catch (\Exception $e) {
                $user->rollback();
                return true;
            }
        });
        return [
            'error' => 0,
            'msg' => '发放成功'
        ];
    }
}